package com.kingmed.kmss.admin.modules.ums.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kingmed.kmss.admin.modules.ums.model.UmsMenu;
import com.kingmed.kmss.admin.modules.ums.model.UmsResource;
import com.kingmed.kmss.admin.modules.ums.model.UmsRole;
import com.kingmed.kmss.admin.modules.ums.service.UmsMenuService;
import com.kingmed.kmss.admin.modules.ums.service.UmsRoleMenuRelationService;
import com.kingmed.kmss.admin.modules.ums.service.UmsRoleResourceRelationService;
import com.kingmed.kmss.admin.modules.ums.service.UmsRoleService;
import com.kingmed.kmss.common.dto.admin.ums.AdminDTO;
import com.kingmed.kmss.common.vo.CommonPage;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 后台用户角色管理
 */
@Controller
@Api(tags = "ums角色管理")
@RequestMapping("/ums/role")
public class UmsRoleController {
    @Autowired
    private UmsRoleService roleService;
    @Autowired
    private UmsMenuService menuService;
    @Autowired
    private UmsRoleMenuRelationService umsRoleMenuRelationService;
    @Autowired
    private UmsRoleResourceRelationService umsRoleResourceRelationService;

    @ApiOperation("添加角色")
    @PostMapping(value = "/create")
    @ResponseBody
    public CommonResponse create(@Validated @RequestBody UmsRole role) {
        boolean success = roleService.create(role);
        if (success) {
            return CommonResponseHelper.success(null);
        }
        return CommonResponseHelper.fail();
    }

    @ApiOperation("修改角色")
    @PostMapping(value = "/update/{id}")
    @ResponseBody
    public CommonResponse update(@Validated @PathVariable Long id, @RequestBody UmsRole role) {
        role.setId(id);
        boolean success = roleService.updateById(role);
        if (success) {
            return CommonResponseHelper.success(null);
        }
        return CommonResponseHelper.fail();
    }

    @ApiOperation("批量删除角色")
    @PostMapping(value = "/delete")
    @ResponseBody
    public CommonResponse<String> delete(@RequestBody List<Long> ids) {
        boolean success = roleService.delete(ids);
        if (success) {
            return CommonResponseHelper.success(null);
        }
        return CommonResponseHelper.fail();
    }


    @ApiOperation("获取所有角色")
    @GetMapping(value = "/listAll")
    @ResponseBody
    public CommonResponse<List<UmsRole>> listAll(@RequestParam(required = false) Integer status) {
        List<UmsRole> roleList = roleService.list(
                new QueryWrapper<UmsRole>().lambda().eq(status != null, UmsRole::getStatus, status));
        return CommonResponseHelper.success(roleList);
    }

    @ApiOperation("根据角色名称分页获取角色列表")
    @GetMapping(value = "/list")
    @ResponseBody
    public CommonResponse<CommonPage<UmsRole>> list(@RequestParam(value = "keyword", required = false) String keyword,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        Page<UmsRole> roleList = roleService.list(keyword, pageSize, pageNum);
        return CommonResponseHelper.success(CommonPage.restPage(roleList));
    }

    @ApiOperation("修改角色状态")
    @PostMapping(value = "/updateStatus/{id}")
    @ResponseBody
    public CommonResponse updateStatus(@PathVariable Long id, @RequestParam(value = "status") Integer status) {
        UmsRole umsRole = new UmsRole();
        umsRole.setId(id);
        umsRole.setStatus(status);
        boolean success = roleService.updateById(umsRole);
        if (success) {
            return CommonResponseHelper.success(null);
        }
        return CommonResponseHelper.fail();
    }

    @ApiOperation("获取角色相关菜单")
    @GetMapping(value = "/listMenu/{roleId}")
    @ResponseBody
    public CommonResponse<List<UmsMenu>> listMenu(@PathVariable Long roleId) {
        List<UmsMenu> roleList = roleService.listMenu(roleId);
        return CommonResponseHelper.success(roleList);
    }

    @ApiOperation("获取角色相关菜单(有子菜单的不查询)")
    @GetMapping(value = "/filterMenu/{roleId}")
    @ResponseBody
    public CommonResponse<List<UmsMenu>> filterMenu(@PathVariable Long roleId) {
        List<UmsMenu> roleList = roleService.filterMenuListByRoleId(roleId);
        return CommonResponseHelper.success(roleList);
    }

    @ApiOperation("获取角色相关资源")
    @GetMapping(value = "/listResource/{roleId}")
    @ResponseBody
    public CommonResponse<List<UmsResource>> listResource(@PathVariable Long roleId) {
        List<UmsResource> roleList = roleService.listResource(roleId);
        return CommonResponseHelper.success(roleList);
    }

    @ApiOperation("给角色分配菜单")
    @PostMapping(value = "/allocMenu/{roleId}")
    @ResponseBody
    public CommonResponse allocMenu(@PathVariable Long roleId, @RequestBody List<Long> menuIds) {
        if (CollectionUtil.isEmpty(menuIds)) {
            return CommonResponseHelper.success();
        }
        menuIds = menuIds.stream().distinct().collect(Collectors.toList());
        int count = roleService.allocMenu(roleId, menuIds);
        return CommonResponseHelper.success(count);
    }

    @ApiOperation("给角色分配菜单（增加父级菜单）")
    @PostMapping(value = "/allocMenuAddParent/{roleId}")
    @ResponseBody
    public CommonResponse<?> allocMenuAddParent(@PathVariable Long roleId, @RequestBody List<Long> menuIds) {
        if (CollectionUtil.isEmpty(menuIds)) {
            umsRoleMenuRelationService.deleteByRoleId(roleId);
            return CommonResponseHelper.success();
        }
        // 添加父级
        List<Long> ids = new ArrayList<>(menuIds);
        for (Long menuId : menuIds) {
            UmsMenu menu = menuService.getBaseMapper().selectById(menuId);
            if (menu != null && !ids.contains(menu.getParentId())) {
                ids.add(menu.getParentId());
            }
        }
        int count = roleService.allocMenu(roleId, ids);
        return CommonResponseHelper.success(count);
    }

    @ApiOperation("给角色分配资源")
    @PostMapping(value = "/allocResource/{roleId}")
    @ResponseBody
    public CommonResponse allocResource(@PathVariable Long roleId, @RequestBody List<Long> resourceIds) {
        if (CollectionUtil.isEmpty(resourceIds)) {
            umsRoleResourceRelationService.deleteByRoleId(roleId);
            return CommonResponseHelper.success();
        }
        int count = roleService.allocResource(roleId, resourceIds);
        return CommonResponseHelper.success(count);
    }

    @ApiOperation("获取角色包含的所有用户")
    @GetMapping(value = "/listUserInRole")
    @ResponseBody
    public CommonResponse<List<AdminDTO>> listUserInRole(@RequestParam Long roleId) {
        List<AdminDTO> adminDTOS = roleService.listUserInRole(roleId);
        return CommonResponseHelper.success(adminDTOS);
    }

}
